package com.example.demo.controller.wx;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.util.FileUtil;
import com.example.demo.util.RestRequestUtil;
import com.example.demo.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description:
 * @author: liyuan
 * @data 2020-11-20 10:34
 */
@RestController
@RequestMapping("/")
public class OCRbinaryController {
    @Value("${test.rootPath}")
    private String rootPath;
    @Value("${test.projectDir}")
    private String projectDir;
    private Logger logger = LoggerFactory.getLogger(AnswerSheetController.class);

    @RequestMapping("OCRbinary")
    public ResultVO ocr(@RequestParam(value = "picture") MultipartFile picture) throws IOException {
        //文件上传保存
        String fileUrl = FileUtil.uploadFile(picture, rootPath, projectDir,
                "OCRbinary", "OCRbinary");
        JSONObject result = binaryMethod(picture.getInputStream());
        return jSON2OCR(result);
    }

    /***
     * ocr识别出的json提取
     * @param result
     * @return
     */
    private ResultVO jSON2OCR(JSONObject result) {
        if (result == null || result.getJSONArray("result") == null) {
            return ResultVO.fail();
        }
        StringBuilder builder = new StringBuilder();
        JSONArray jsonArray = result.getJSONArray("result");
        for (JSONObject obj : jsonArray.toJavaList(JSONObject.class)) {
            builder.append(obj.getString("text"));
        }
        return new ResultVO(1000, builder.toString());
    }

    /***
     *  封装的rest请求
     * @param inputStream
     * @return
     * @throws IOException
     */
    private JSONObject binaryMethod(InputStream inputStream) throws IOException {
        String url = "http://49.232.94.107:2913/subjectocr";
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity entity = RestRequestUtil.octetStreamEntity(inputStream);
        String result = restTemplate.postForObject(url, entity, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        logger.info("识别返回数据{}", jsonObject.toJSONString());
        return jsonObject;
    }


}
